/* PidFile.cpp */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "PidFile.h"

#ifndef ASSERT
	#include <assert.h>
	#define ASSERT(x) assert(x);
#endif



//-----------------------------------------------------------------------------
// Constructor
PidFile::PidFile() {
	_pid = 0;
	_pid_file = NULL;
}


//-----------------------------------------------------------------------------
// Deconstructor.
PidFile::~PidFile() {
	// Make sure we still have as much data integrity as we can check for.
	ASSERT((_pid == 0 && _pid_file == NULL) || (_pid > 1 && _pid_file != NULL));

	if (_pid > 1) {
		Remove();
	}
}

//-----------------------------------------------------------------------------
// We have a PID number, and a file path.  We need to make sure that we can 
// write to the file, and write the number to it.  
void PidFile::Create(const pid_t pid, const char *pid_file) {
	ASSERT(pid > 1 && pid_file != NULL);
	ASSERT(_pid == 0 && _pid_file == NULL);
	
	FILE *fp;
	if (pid_file == NULL)
		return;
	
	if ((fp = fopen(pid_file, "w")) == NULL) {
		fprintf(stderr, "Could not open the pid file %s for writing\n", pid_file);
		return;
	}
	
	fprintf(fp,"%ld\n", (long)pid);
	if (fclose(fp) == -1) {
		fprintf(stderr, "Could not close the pid file %s.\n", pid_file);
		return;
	}
}


//-----------------------------------------------------------------------------
// Assuming that we created a pid file, then we will want to remove it.
void PidFile::Remove(void) {
	ASSERT(_pid > 1 && _pid_file != NULL);

  if (_pid_file != NULL) {
  	if (unlink(_pid_file) != 0) {
			fprintf(stderr, "Could not remove the pid file %s.\n", _pid_file);
		}
	}
	_pid = 0;
	_pid_file = NULL;
}




